<template></template>

<script>
import net from "net";

export default {
  //发送数据
  async send(json, ip, port) {
    console.log("sendData... waiting,json->", json);
    return new Promise((resolve, reject) => {
      let client = new net.Socket(); //后期改缓存连接
      client.connect({
        host: ip,
        port: port,
      });

      //客户端与服务器建立连接触发
      client.on("connect", () => {
        client.write(JSON.stringify(json));
      });

      //客户端接收数据触发
      client.on("data", (data) => {
        client.end();
        resolve(this.safeJsonParse(data.toString()));
      });

      client.on("error", (error) => {
        reject(error);
      });
    });
  },

  safeJsonParse(data) {
    try {
      return JSON.parse(data);
    } catch (err) {
      console.log("data :>> ", data);
      return null;
    }
  },
};
</script>

<style>
</style>
